<template>
  <img :src="loadUrl" alt="" ref="imageRef" />
</template>

<script lang="ts" setup>
import { defineProps, onMounted, ref, watch } from 'vue'
interface PropsType {
  src: string
  alt: string
}
const props = defineProps<PropsType>()
const loadUrl = ref('https://img.zcool.cn/community/0196fa582abab6a84a0d304f899eaf.gif')
const imageRef = ref<HTMLElement>()

watch(props, () => {
  loadUrl.value = props.src
})

onMounted(() => {
  if (imageRef.value) {
    // 新建窗口监听对象
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].intersectionRatio <= 0) {
        // 视口外
        return
      }
      // 视口内
      loadUrl.value = props.src
    })
    // 监听节点
    observer.observe(imageRef.value)
  }
})
</script>

<script lang="ts">
export default {
  name: 'LazyLoadImage'
}
</script>
